<?php
/**
 * Created by PhpStorm.
 * User: eddy
 * Date: 2018/4/23
 * Time: 21:51
 */

namespace iBrand\Shop\Server\Http\Controllers\O2oUser;


use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Store;

class ShopLocalController extends Controller
{
    /**
     * 根据两点间的经纬度计算距离
     * @param $lng1
     * @param $lat1
     * @param $lng2
     * @param $lat2
     * @return int
     */
    protected function getDistance($lng1, $lat1, $lng2, $lat2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    public function getLocalShop()
    {
        $lng = request('lng');
        $lat = request('lat');
        $shops = Store::where('is_enable', 1)->get();
        $distance = [];
        if (count($shops) > 0) {
            foreach ($shops as $item) {
                if ($item->lng AND $item->lat) {
                    $distance[$item->id] = $this->getDistance($lng, $lat, $item->lng, $item->lat);
                }
            }
            if (count($distance) > 0) {
                $minDistance = min($distance);
                if ($minDistance <= 1000) {
                    $shop = Store::find(array_keys($distance, $minDistance)[0]);
                    return $this->api(['shop' => $shop]);
                } else {
                    return $this->api();
                }
            }
            return $this->api();
        }
        return $this->api();
    }
}